//
//  PartyDownloadDetailController.m
//  UESTCPioneer
//
//  Created by Apple on 14-9-28.
//  Copyright (c) 2014年 Sway. All rights reserved.
//

#import "PartyDownloadDetailController.h"
#import "AppDelegate.h"

@interface PartyDownloadDetailController ()
{
    NSString * urlString;
    NSTimer * timer;
    long long totalBytes;
    NSURLSessionDownloadTask * _downloadTask;
    NSData * _partialDownload;
    BOOL _haveDownload;
}
@property (nonatomic,strong) UILabel * nameLabel;
//@property (nonatomic,strong) UILabel * adressLabel;
@property (nonatomic,strong) UILabel * stateLabel;
@property (nonatomic,strong) UIButton * downloadButton;
@property (nonatomic,strong) NSString * fileName;
@property (nonatomic,strong) UIProgressView * progress;
/*修改*/
@property (nonatomic,strong) UILabel * sizeLabel;
@property (nonatomic,strong) NSString * fileSize;
@property (nonatomic,strong) UIButton * deleteButton;
@property (nonatomic,strong) UIButton * readButton;//预览按钮
@property (nonatomic,strong) NSNumber * fileTheId;
@property (nonatomic) BOOL recordFlag;
 /**/
@property (assign, nonatomic) long long totalBytesHaveDownload;
@property (strong, nonatomic) UIDocumentInteractionController *documentInteractionController;

@end

@implementation PartyDownloadDetailController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    return self;
}

-(id) initWithFileName:(NSString *)fileName URLString:(NSString *)str fileSize:(NSString *)fileSize theId:(NSNumber *)theId{
    if (self) {
        _fileName = fileName;
        urlString = str;
        _fileSize = fileSize;
        _fileTheId = theId;
    }
    return self;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    _recordFlag = NO;
    
    self.title = @"下载";
    self.view.backgroundColor = [UIColor whiteColor];
    
    _nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(85, 5,self.view.frame.size.width - 90, 50)];
    _nameLabel.adjustsFontSizeToFitWidth = YES;
    [_nameLabel setNumberOfLines:0];
    _nameLabel.text = _fileName;
    [_nameLabel setFont:[UIFont systemFontOfSize:14]];
    
    UILabel *fileLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 5, 80, 50)];
    fileLabel.text = @"文件名 :";
    UILabel * state = [[UILabel alloc] initWithFrame:CGRectMake(5, _nameLabel.frame.origin.y + _nameLabel.frame.size.height + 10, 120, 50)];
    state.text = @"下载状态 :";
    _stateLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.progress.frame.origin.x , state.frame.origin.y + 13, 50, 50)];
    [_stateLabel setTextColor:[UIColor grayColor]];
    [_stateLabel setFont:[UIFont systemFontOfSize:10]];
    _sizeLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.progress.frame.origin.x + self.progress.frame.size.width - 30 , state.frame.origin.y + 13, 50, 50)];
    _sizeLabel.text = self.fileSize;
    [_sizeLabel setFont:[UIFont systemFontOfSize:10]];
    [_sizeLabel setTextColor:[UIColor grayColor]];
    [self.view addSubview:_sizeLabel];
    
    for (int i = 0; i < 2; i ++) {
        UIView * bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 60+60*i, 320, 1)];
        bgView.backgroundColor = [UIColor redColor];
        [self.view addSubview:bgView];
    }
    
    NSString* filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:self.fileName];
    NSLog(@"self.fileName = %@",self.fileName);
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    if ([fileManager fileExistsAtPath:filePath]) {
        [self.progress setProgress:1 animated:NO];
        [self.stateLabel setText: @"100%"];
        [self.downloadButton setTitle:@"删除文件" forState:UIControlStateNormal];
        [self.downloadButton setTitle:@"删除文件" forState:UIControlStateSelected];
        [self.downloadButton setTitle:@"删除文件" forState:UIControlStateHighlighted];
        [self.view addSubview:self.readButton];
        _haveDownload = YES;
    }else{
        [self.progress setProgress:0 animated:NO];
        [self.stateLabel setText: @"0%"];
        _haveDownload = NO;
    }
    
    [self.view addSubview:self.downloadButton];
    [self.view addSubview:_nameLabel];
    [self.view addSubview:fileLabel];
    [self.view addSubview:_stateLabel];
    [self.view addSubview:self.progress];
    [self.view addSubview:state];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self getDownloadController];
    if (totalBytes == 0){totalBytes =0.001;}
    timer =  [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(function) userInfo:nil repeats:YES];
    //每0.2秒运行一次function方法。
    //开启定时器
    [timer setFireDate:[NSDate distantPast]];
}

-(void)getDownloadController{
    int i = 0;
    for (NSDictionary * dic in [self appDelegate].downloadController) {
        NSNumber * fileId = dic[@"id"];
        if ([fileId isEqualToNumber:_fileTheId]) {
            self.totalBytesHaveDownload = [dic[@"total"] longLongValue];
            break;
        }else i++;
    }
    
    if (i == [self appDelegate].downloadController.count) {
        NSMutableDictionary * dict = [NSMutableDictionary dictionary];
        [dict setObject:_fileTheId forKey:@"id"];
        [dict setObject:@(self.totalBytesHaveDownload) forKey:@"download"];
        [dict setObject:@(1) forKey:@"total"];
        [[self appDelegate].downloadController addObject:dict];
    }
}

-(void)function{
    
    for (NSDictionary * dic in [self appDelegate].downloadController) {
        NSNumber * fileId = dic[@"id"];
        float progress = 0.0;
        if ([fileId isEqualToNumber:_fileTheId]) {
            
            if (_haveDownload) {//增加_haveDownload的目的是解决当重新启动app之后，对已下载的文件其进度条仍然显示0%的问题。所以对该属性不用控制的太严格。
                [self.stateLabel setText: @"100%"];
                [self.progress setProgress:1.0f animated:YES];
            } else {
                self.totalBytesHaveDownload = [dic[@"download"] longLongValue];
                totalBytes = [dic[@"total"] longLongValue];
                progress = self.totalBytesHaveDownload*1.0/totalBytes;
                [self.progress setProgress:progress animated:YES];
                self.stateLabel.text = [NSString stringWithFormat:@"%.0f%%",progress*100];
            }
            
            if (progress == 1.000000) {
                [self.stateLabel setText: @"100%"];
                [self.view addSubview:self.readButton];
                [self.downloadButton setTitle:@"删除文件" forState:UIControlStateNormal];
                [self.downloadButton setTitle:@"删除文件" forState:UIControlStateSelected];
                [self.downloadButton setTitle:@"删除文件" forState:UIControlStateHighlighted];
                
                //向服务器发送下载信息，以便于服务器端进行统计
                if (!_recordFlag) {
                     [self sendToServer];
                    _recordFlag = YES;
                }
            }
            break;
        }
    }
}

-(void)sendToServer{
    NSLog(@"哈哈哈哈哈哈哈哈");
    //ht tp://115.28.239.113:8080/ScienceApp/AdminRecord.do?type=dangkeFile&userName=&userId=&doc_name=(utf-8编码一次)
    NSDictionary *requestData=@{@"type":@"dangkeFile"
                                ,@"userId":[constant getUserId]
                                ,@"userName":[constant getUserName]
                                ,@"doc_name":[helper urlencode:_fileName]
                                };
    [NetworkCenter AFRequestWithRecordData:requestData SuccessBlock:^(AFHTTPRequestOperation *operation, id resultObject) {
        //        NSArray *arr = [NSJSONSerialization JSONObjectWithData:resultObject options:NSJSONReadingMutableLeaves error:nil];
        //        NSDictionary *dic =arr[0];
        //        NSLog(@"返回值dic = %@",dic);
        //        if ([dic[@"result"] isEqualToString:@"success"]){
        //            [Alert showAlert:@"上传成功"];
        //        } else {
        //        }
    } FailureBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        [Alert showAlert:@"网络连接出错"];
        NSLog(@"网络连接出错 = %@",error.localizedDescription);
    }];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    //关闭定时器
    [timer setFireDate:[NSDate distantFuture]];
}

//取得当前程序的委托
-(AppDelegate *)appDelegate{
    return (AppDelegate *) [[UIApplication sharedApplication] delegate];
}


-(void)webViewDidFinishLoad:(UIWebView *)webView{
    NSString *meta = [NSString stringWithFormat:@"document.getElementsByName(\"viewport\")[0].content = \"width=%f, initial-scale=2.0, minimum-scale=1.0, maximum-scale=2.5, user-scalable=yes\"", webView.frame.size.width];
    [webView stringByEvaluatingJavaScriptFromString:meta];
    
}

/*修改*/
-(UIProgressView *)progress{
    if (!_progress) {
        self.progress= [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
        [self.progress setFrame:CGRectMake(105, _nameLabel.frame.origin.y + _nameLabel.frame.size.height + 33, 180, 10)];
    }
    return _progress;
}

/*最新修改*/
-(UIButton *)readButton{
    if (!_readButton) {
        _readButton = [[UIButton alloc] initWithFrame:CGRectMake(self.progress.frame.origin.x + self.progress.frame.size.width + 5, self.progress.frame.origin.y - 15, 30.0, 30.0)];
        [_readButton setBackgroundImage:[UIImage imageNamed:@"partyreport.png"] forState:UIControlStateNormal];
        [_readButton setBackgroundImage:[UIImage imageNamed:@"partyreport.png"] forState:UIControlStateHighlighted];
        [_readButton setBackgroundImage:[UIImage imageNamed:@"partyreport.png"] forState:UIControlStateSelected];
        
        [_readButton addTarget:self action:@selector(readButtonClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _readButton;
}
/**/
-(UIButton *)downloadButton{
    if (!_downloadButton) {
        _downloadButton = [[UIButton alloc] initWithFrame:CGRectMake(110, 150, 100.0, 30.0)];
        [_downloadButton setBackgroundImage:[UIImage imageNamed:@"filedl"] forState:UIControlStateNormal];
        [_downloadButton setBackgroundImage:[UIImage imageNamed:@"filedl"] forState:UIControlStateHighlighted];
        [_downloadButton setBackgroundImage:[UIImage imageNamed:@"filedl"] forState:UIControlStateSelected];
        [_downloadButton setTitle:@"下载文件" forState:UIControlStateSelected];
        [_downloadButton setTitle:@"下载文件" forState:UIControlStateNormal];
        [_downloadButton setTitle:@"下载文件" forState:UIControlStateHighlighted];
        [_downloadButton setTitleEdgeInsets:UIEdgeInsetsMake(5, 30, 5, 5)];
        [_downloadButton.titleLabel setFont:[UIFont systemFontOfSize:15]];
        _downloadButton.titleLabel.textColor = [UIColor whiteColor];
        
        [_downloadButton addTarget:self action:@selector(downloadButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _downloadButton;
}

-(void)downloadButtonClick:(UIButton *)sender{
    
    NSString* filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:self.fileName];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:filePath]) {
        /*删除文件*/
        [self deleteButtonClick];
        
    }else if([_downloadButton.titleLabel.text isEqualToString:@"下载文件"]){
        
        NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
        NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
        NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate:self delegateQueue: [NSOperationQueue mainQueue]];
        NSURLSessionDownloadTask * downloadTask =[ defaultSession downloadTaskWithURL:url];
        [downloadTask resume];
        _downloadTask = downloadTask;
        [_downloadButton setTitle:@"取消下载" forState:UIControlStateSelected];
        [_downloadButton setTitle:@"取消下载" forState:UIControlStateNormal];
        [_downloadButton setTitle:@"取消下载" forState:UIControlStateHighlighted];
        
    }else if([_downloadButton.titleLabel.text isEqualToString:@"取消下载"]){
        [_downloadButton setTitle:@"下载文件" forState:UIControlStateSelected];
        [_downloadButton setTitle:@"下载文件" forState:UIControlStateNormal];
        [_downloadButton setTitle:@"下载文件" forState:UIControlStateHighlighted];
        
        for (int i = 0; i < [self appDelegate].downloadController.count;i++ ) {
            NSDictionary * dic = [self appDelegate].downloadController[i];
            NSNumber * fileId = dic[@"id"];
            if ([fileId isEqualToNumber:_fileTheId]) {
                [[self appDelegate].downloadController  removeObject:dic];
            }
        }
        NSMutableDictionary * dict = [NSMutableDictionary dictionary];
        [dict setObject:_fileTheId   forKey:@"id"];
        [dict setObject:@(0) forKey:@"download"];
        [dict setObject:@(1) forKey:@"total"];
        [[self appDelegate].downloadController addObject:dict];
        
        _haveDownload = NO;
        [self.stateLabel setText: @"0%"];
        [_downloadTask cancel];
    }
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#pragma mark - URLSessionDownload Delegate
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
    //    NSLog(@"Temporary File :%@\n", location);
    NSError *err = nil;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *docsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    
    NSURL *docsDirURL = [NSURL fileURLWithPath:[docsDir stringByAppendingPathComponent:self.fileName]];
    
    NSLog(@"docsDirURL = %@",docsDirURL);
    if ([fileManager moveItemAtURL:location
                             toURL:docsDirURL
                             error: &err])
    {
        [self changeStatusType:1];
        //        [self.view addSubview:self.readButton];
        //        [self.downloadButton setTitle:@"删除文件" forState:UIControlStateNormal];
        //        [self.downloadButton setTitle:@"删除文件" forState:UIControlStateSelected];
        //        [self.downloadButton setTitle:@"删除文件" forState:UIControlStateHighlighted];
        
        if (docsDirURL) {
            
            // Initialize Document Interaction Controller
            self.documentInteractionController = [UIDocumentInteractionController interactionControllerWithURL:docsDirURL];
            // Configure Document Interaction Controller
            [self.documentInteractionController setDelegate:self];
            // Preview PDF
            BOOL isValid = [self.documentInteractionController presentPreviewAnimated:YES];
            if (!isValid) {
                [Alert showAlert:@"没有可用的软件!"];
            }
        }
        
        /*
         NSURLRequest *request = [NSURLRequest requestWithURL:docsDirURL];
         UIWebView * webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, self.view.frame.size.height)];
         [webView loadRequest:request];
         [webView setScalesPageToFit:YES];
         webView.scrollView.bounces = NO;
         [self changeStatusType:1];
         [self.view addSubview:self.readButton];
         [self.downloadButton setTitle:@"删除文件" forState:UIControlStateNormal];
         [self.downloadButton setTitle:@"删除文件" forState:UIControlStateSelected];
         [self.downloadButton setTitle:@"删除文件" forState:UIControlStateHighlighted];
         
         UIViewController * controller = [[UIViewController alloc] init];
         [controller.view addSubview:webView];
         [self.navigationController pushViewController:controller animated:YES];
         */
    }
    else
    {
        //        NSLog(@"failed to move: %@",[err userInfo]);
    }
}

-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
    _totalBytesHaveDownload = totalBytesWritten;
    //    float progress = _totalBytesHaveDownload*1.0/totalBytesExpectedToWrite;
    if ([self appDelegate].isUsed) {
        [Alert showAlert:@"请稍后"];
        return;
    }
    
    for (int i = 0; i < [self appDelegate].downloadController.count;i++ ) {
        NSDictionary * dic = [self appDelegate].downloadController[i];
        NSNumber * fileId = dic[@"id"];
        if ([fileId isEqualToNumber:_fileTheId]) {
            [[self appDelegate].downloadController  removeObject:dic];
        }
    }
    NSMutableDictionary * dict = [NSMutableDictionary dictionary];
    [dict setObject:_fileTheId   forKey:@"id"];
    [dict setObject:@(_totalBytesHaveDownload) forKey:@"download"];
    [dict setObject:@(totalBytesExpectedToWrite) forKey:@"total"];
    [[self appDelegate].downloadController addObject:dict];
    
    [self appDelegate].isUsed = NO;
    /* modified for auto change progress
     dispatch_async(dispatch_get_main_queue(),^ {
     [self.progress setProgress:progress animated:YES];
     self.stateLabel.text = [NSString stringWithFormat:@"%.0f%%",progress*100];
     NSLog(@"progress = %f",progress);
     });
     */
}

-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes{
}

-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
}

/*最新修改*/
-(void)deleteButtonClick{
    UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"提示"
                                                         message:@"确定要删除文件?"
                                                        delegate:self
                                               cancelButtonTitle:@"确定"
                                               otherButtonTitles:@"取消",nil];
    [alertView show];
    
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex ==0) {
        NSString* filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:self.fileName];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        if ([fileManager fileExistsAtPath:filePath]) {
            [fileManager removeItemAtPath:filePath error:nil];
            [self.downloadButton setTitle:@"下载文件" forState:UIControlStateNormal];
            [self.downloadButton setTitle:@"下载文件" forState:UIControlStateSelected];
            [self.downloadButton setTitle:@"下载文件" forState:UIControlStateHighlighted];
            [self.progress setProgress:0 animated:NO];
            
            for (int i = 0; i < [self appDelegate].downloadController.count;i++ ) {
                NSDictionary * dic = [self appDelegate].downloadController[i];
                NSNumber * fileId = dic[@"id"];
                if ([fileId isEqualToNumber:_fileTheId]) {
                    [[self appDelegate].downloadController  removeObject:dic];
                }
            }
            
            NSMutableDictionary * dict = [NSMutableDictionary dictionary];
            [dict setObject:_fileTheId   forKey:@"id"];
            [dict setObject:@(0) forKey:@"download"];
            [dict setObject:@(1) forKey:@"total"];
            [[self appDelegate].downloadController addObject:dict];
            [self appDelegate].isUsed = NO;
            
            _haveDownload = NO;
            [self.stateLabel setText: @"0%"];
            [Alert showAlert:@"已删除!"];
            [self.readButton removeFromSuperview];
            [self changeStatusType:2];
        }
    }
}

-(void)changeStatusType:(NSInteger)type{
    //    NSLog(@"改变视频文件的下载状态!");
    NSArray * array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString * filePath ;
    if (self.isFile) {
        filePath =[array[0] stringByAppendingPathComponent:@"downloadfile.plist"];
    }
    if (self.isMajor) {
        filePath =[array[0] stringByAppendingPathComponent:@"downloadmajor.plist"];
    } else {
        filePath =[array[0] stringByAppendingPathComponent:@"downloadResourceFile.plist"];
    }
    
    NSNumber *status ;
    NSFileManager * fileManager = [NSFileManager defaultManager ];
    if (![fileManager fileExistsAtPath:filePath]) {//不存在就创建
        NSMutableArray * array = [NSMutableArray array];
        [array addObject:[NSString stringWithFormat:@"%@",_fileTheId]];
        [array writeToFile:filePath atomically:YES];
        if (type == 1) {
            status = @1;
        }
        if (type == 2) {
            status = @2;
        }
    }else{//存在 -- 添加或删除
        NSMutableArray * array = [NSMutableArray arrayWithContentsOfFile:filePath];
        
        if (type == 1) {//添加
            [array addObject:[NSString stringWithFormat:@"%@",_fileTheId]];
            status = @1;
        }else if (type == 2){//删除
            [array removeObject:[NSString stringWithFormat:@"%@",_fileTheId]];
            status = @2;
        }
        [fileManager removeItemAtPath:filePath error:nil];
        [array writeToFile:filePath atomically:YES];
        
        NSLog(@"filePath = %@",filePath);
    }
    [self.downLoadFinishDelegate downLoadFinishWithIndexPath:status fileTheId:_fileTheId];
}
#pragma mark 阅读按钮
-(void)readButtonClick{
    
    NSString* filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:self.fileName];
    NSLog(@"filePath = %@",filePath);
    NSURL *fileURL = [NSURL fileURLWithPath:filePath];
    //    NSURL *URL = [[NSBundle mainBundle] URLForResource:@"sample" withExtension:@"pdf"];
    
    if (fileURL) {
        
        self.documentInteractionController = [UIDocumentInteractionController interactionControllerWithURL:fileURL];
        [self.documentInteractionController setDelegate:self];
        
        BOOL isValid = [self.documentInteractionController presentOpenInMenuFromRect:[self.readButton frame] inView:self.view animated:YES];
        if (!isValid) {
            //            [Alert showAlert:@"没有可用的软件!"];
            NSURLRequest *request = [NSURLRequest requestWithURL:fileURL];
            UIWebView * webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, self.view.frame.size.height)];
            [webView loadRequest:request];
            [webView setScalesPageToFit:YES];
            webView.scrollView.bounces = NO;
            
            UIViewController * controller = [[UIViewController alloc] init];
            [controller.view addSubview:webView];
            [self.navigationController pushViewController:controller animated:YES];
        }
    }
}

#pragma mark -
#pragma mark Document Interaction Controller Delegate Methods
- (UIViewController *) documentInteractionControllerViewControllerForPreview: (UIDocumentInteractionController *) controller {
    return self;
}
/**/
@end
